import { Spin, Tree, TreeSelect } from 'antd';
import React, { useState } from 'react';
import { useDeepCompareEffect, useUpdateEffect } from 'ahooks';
import isEqual from 'lodash/isEqual';
import useCatalogTree from '@/hooks/UseCatalogTree';
import { findParentKeysRecursive } from '@/pages/ProcessManager/CatalogTree';
import { isFunction } from 'lodash';

function renderTree(data, disabledKeys) {
  return data.map(node => (
    <Tree.TreeNode
      title={node.title}
      key={node.key}
      disabled={disabledKeys.includes(node.key)}
      isLeaf={node.leaf}
      value={node.catalogId}
    >
      {node.children.length && renderTree(node.children, disabledKeys)}
    </Tree.TreeNode>
  ));
}

function CatalogTreeSelect({ code, disabledKeys = [], ...props }) {
  const { value } = props;
  const { data, nodeList, loading } = useCatalogTree(code);
  const [expandedKeys, setExpandedKeys] = useState([]);

  useDeepCompareEffect(() => {
    const nodesToSearch = nodeList.filter(node => node.catalogId === value);
    const parentKeys = findParentKeysRecursive(nodesToSearch, nodeList);
    setExpandedKeys(parentKeys);
  }, [nodeList, value]);

  if (!loading) {
    disabledKeys = isFunction(disabledKeys) ? disabledKeys(nodeList) : disabledKeys;
  }

  return (
    <Spin spinning={loading}>
      <TreeSelect
        treeExpandedKeys={expandedKeys}
        onTreeExpand={setExpandedKeys}
        placeholder="--请选择--"
        allowClear
        {...props}
      >
        {renderTree(data, disabledKeys)}
      </TreeSelect>
    </Spin>
  );
}

export default CatalogTreeSelect;
